package com.phpxiu.app.okhttp;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @file
 * @brief OKHttp请求非UI回调
 * @author 吴金洲
 * @note  OKHttp请求非UI回调，响应结果不需要用来更新UI界面时，可设置此类回调
 *
 */
public abstract class OKHttpCallback extends Handler implements Callback {
    public final static int HANDLE_SUCCESS=-0x7f9eb;//处理成功响应，-522731
    public final static int HANDLE_FAILED=-0x53084;//处理失败响应，-340100
    private boolean isRefreshUi=true;

    protected OKHttpCallback(boolean isRefreshUi) {
        this.isRefreshUi = isRefreshUi;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        if(isRefreshUi) {
            Message msg = obtainMessage();
            msg.what = HANDLE_FAILED;
            msg.obj = "Failed,IOException!";
            sendMessage(msg);
        }else{
            onErr("Failed,IOException!");
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if(isRefreshUi) {
            Message msg = obtainMessage();
            if (response.isSuccessful()) {
                msg.what = HANDLE_SUCCESS;
                msg.obj = response.body().string();
            } else {
                msg.what = HANDLE_FAILED;
                msg.obj = response.toString();
            }
            sendMessage(msg);
        }else{
            try {
                onSuccess(response.body().string());
            }catch (NullPointerException e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case HANDLE_SUCCESS:
                onSuccess(msg.obj == null ? null : msg.obj.toString());
                break;
            case HANDLE_FAILED:
                onErr(msg.obj==null?null:msg.obj.toString());
                break;
            default:
                break;
        }
    }

    /**
     * 响应成功
     * @param result 响应中的数据串
     */
    public abstract void onSuccess(String result);

    /**
     * 响应失败
     * @param msg 失败的描述信息
     */
    public abstract void onErr(String msg);
}
